<?php

namespace app\service;

use app\exception\ErrnoPlus;
use app\model\SendNoticeTableModel;
use app\service\cache\SendNoticeTableCacheService;
use share\exception\ApiException;
use share\service\BaseModelService;
use share\utils\Helper;

class SendNoticeTableService extends BaseModelService{

    public static function getModel()
    {
        return new SendNoticeTableModel;
    }

    public static function getAllNotice($language){        
        $sendInfo = SendNoticeTableCacheService::getAllByFilter(['status'=> 1],['first_time','desc']);
        if(empty($sendInfo)){
            return null;
        }
        $res = [];
        foreach ($sendInfo as $info) {
            $tmp = [];
            if ($info["model"] === 1) {
                $tmp["model"] = 1;
                $tmp["beginTime"] = $info["begin_time"];
                $tmp["endTime"] = $info["end_time"];
                $tmp["level"] = $info["level"];
                $res[] = $tmp;
                continue;
            }
            if ($info["language"] === $language) {
                $tmp["model"] = 2;
                $tmp["message"] = $info["message"];
                $tmp["level"] = $info["level"];
                $info[] = $tmp;
            }
        }
        return $res;
    }

    public static function getAllNoticeByLanguage($language){
        $sendInfo = SendNoticeTableCacheService::getAllByFilter(['status'=> 1,"language"=> $language],['first_time','desc']);
        if(empty($sendInfo)){
            return null;
        }
        $res = [];
        foreach ($sendInfo as $info) {
            $res[] = [
                "model" => $info["model"],
                "beginTime" => $info["begin_time"],
                "endTime" => $info["end_time"],
                "level" => $info["level"],
                "title" => $info["title"],
                "message" => $info["message"]
            ];
        }
        return $res;
    }

    public static function addNotice($param){
        $item  = Helper::arrayCamelKeyToUnderscore($param);
        self::add($item);
        SendNoticeTableCacheService::reflushAll();
    }

    public static function updateNotice($param){
        $id =  $param['id'];
        unset($param['id']);
        $origin = self::getBase($id);
        if(empty($origin)){
            throw new ApiException("origin data is not exist",ErrnoPlus::COMMON_ERROR);
        }
        $item = Helper::arrayCamelKeyToUnderscore($param);
        $update = [];
        foreach($item as $key => $val){
            if($val != $origin[$key]){
                $update[$key] = $val;
            }
        }
        if(count($update) > 0){
            self::update($id,$update);
        }
        SendNoticeTableCacheService::reflushAll();
    }

    public static function delNotice($id){
        self::del($id);
        SendNoticeTableCacheService::reflushAll();
    }

    public static function buildCondition($filter)
    {
        return [];
    }
}